package org.jeecg.modules.deviceInfo.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.deviceBaseInfo.entity.DeviceBaseInfo;
import org.jeecg.modules.deviceBaseInfo.service.IDeviceBaseInfoService;
import org.jeecg.modules.deviceInfo.entity.DeviceInfo;
import org.jeecg.modules.deviceInfo.service.IDeviceInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.userRate.entity.UserRate;
import org.jeecg.modules.userRate.service.IUserRateService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 设备基础费率表
 * @Author: jeecg-boot
 * @Date:   2025-03-28
 * @Version: V1.0
 */
@Api(tags="设备基础费率表")
@RestController
@RequestMapping("/deviceInfo/deviceInfo")
@Slf4j
public class DeviceInfoController extends JeecgController<DeviceInfo, IDeviceInfoService> {
	@Autowired
	private IDeviceInfoService deviceInfoService;
	 @Autowired
	 private IDeviceBaseInfoService deviceBaseInfoService;

	 @Autowired
	 private IUserRateService userRateService;


	/**
	 * 分页列表查询
	 *
	 * @param deviceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-分页列表查询")
	@ApiOperation(value="设备基础费率表-分页列表查询", notes="设备基础费率表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(DeviceInfo deviceInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		deviceInfo.setIsNew(1);
		QueryWrapper<DeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(deviceInfo, req.getParameterMap());
		Page<DeviceInfo> page = new Page<DeviceInfo>(pageNo, pageSize);
		IPage<DeviceInfo> pageList = deviceInfoService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	 @AutoLog(value = "设备基础费率表-历史分页列表查询")
	 @ApiOperation(value="设备基础费率表-历史分页列表查询", notes="设备基础费率表-历史分页列表查询")
	 @GetMapping(value = "/listHis")
	 public Result<?> queryPageListlistHis(DeviceInfo deviceInfo,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 deviceInfo.setIsNew(0);
		 QueryWrapper<DeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(deviceInfo, req.getParameterMap());
		 Page<DeviceInfo> page = new Page<DeviceInfo>(pageNo, pageSize);
		 IPage<DeviceInfo> pageList = deviceInfoService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }


	 // 辅助方法：计算单个物料的费用（处理null值）
	 private static BigDecimal calculateMaterialCost(BigDecimal monthUse, BigDecimal price) {
		 if (monthUse == null || price == null || price == BigDecimal.valueOf(0)) {
			 return null;
		 }
		 return monthUse.multiply(price);
	 }
	/**
	 *   添加
	 *
	 * @param deviceInfo
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-添加")
	@ApiOperation(value="设备基础费率表-添加", notes="设备基础费率表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody DeviceInfo deviceInfo) {

		DeviceBaseInfo deviceBaseInfo = deviceBaseInfoService.list().get(0);
		DeviceInfo deviceInfoS= deviceInfoService.getOne(new QueryWrapper<DeviceInfo>().eq("device_type",deviceInfo.getDeviceType()).eq("device_name_model",deviceInfo.getDeviceNameModel()));
		if(deviceInfoS!=null){


			throw new JeecgBootException("该信息已存在，请重新检查后导入！"+deviceInfoS.getDeviceType()+"/"+deviceInfoS.getDeviceNameModel());
		}

		// 1. 计算 oldValueW（除以10000，保留4位小数）
		BigDecimal tenThousand = BigDecimal.valueOf(10000);
		if(deviceInfo.getOldValue()!=null){
			BigDecimal oldValueW = deviceInfo.getOldValue()
					.divide(tenThousand, 4, RoundingMode.HALF_UP);
			deviceInfo.setOldValueW(oldValueW);
		}



       // 2. 计算 directRate（设备折旧费率）
		BigDecimal depreciationFactor = BigDecimal.ONE.subtract(deviceBaseInfo.getSbCz());
		BigDecimal usageInSeconds = BigDecimal.valueOf(3600);
		BigDecimal depreciationRate = BigDecimal.ZERO;
		if( deviceInfo.getOldValue()!=null){
			BigDecimal numerator = deviceInfo.getOldValue().multiply(depreciationFactor);
			BigDecimal denominator = new BigDecimal(deviceInfo.getUseMonth())
					.multiply(deviceBaseInfo.getSbZjDay())
					.multiply(deviceBaseInfo.getSbZjHour())
					.multiply(usageInSeconds);

			 depreciationRate = numerator.divide(denominator, 6, RoundingMode.HALF_UP);
			deviceInfo.setDepreciationRate(depreciationRate);
		}else{
			deviceInfo.setDepreciationRate(BigDecimal.valueOf(0));
		}

		//3 电费率
		BigDecimal powRate = BigDecimal.valueOf(0);
		if(deviceInfo.getPower()==null || deviceInfo.getPowerConsumptionRatio()==null){
			deviceInfo.setPowRate(BigDecimal.valueOf(0));
		}else{
			powRate = deviceInfo.getPower().multiply(deviceInfo.getPowerConsumptionRatio()).multiply(deviceBaseInfo.getDf()).divide(BigDecimal.valueOf(3600),5,RoundingMode.HALF_UP);
			deviceInfo.setPowRate(powRate.setScale(5, BigDecimal.ROUND_HALF_UP));
		}

		//机物料费率
		// 4. 计算所有物料的月总费用（material1MonthUse * material1Price + ...）
		BigDecimal materRate = Stream.of(
				// 使用 Optional 包装，避免 NPE
				calculateMaterialCost(deviceInfo.getMaterial1MonthUse(), deviceInfo.getMaterial1Price()),
				calculateMaterialCost(deviceInfo.getMaterial2MonthUse(), deviceInfo.getMaterial2Price()),
				calculateMaterialCost(deviceInfo.getMaterial3MonthUse(), deviceInfo.getMaterial3Price()),
				calculateMaterialCost(deviceInfo.getMaterial4MonthUse(), deviceInfo.getMaterial4Price()),
				calculateMaterialCost(deviceInfo.getMaterial5MonthUse(), deviceInfo.getMaterial5Price()),
				calculateMaterialCost(deviceInfo.getMaterial6MonthUse(), deviceInfo.getMaterial6Price())
		)
				.filter(Objects::nonNull) // 过滤掉为null的物料费用
				.reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有非空物料费用

      // 5. 按基准值和时间单位折算费率
		if (materRate.compareTo(BigDecimal.ZERO) > 0) {
			materRate = materRate.divide(deviceBaseInfo.getJwlxhDay(), 5, RoundingMode.HALF_UP)
					.divide(deviceBaseInfo.getJwlxhHour(), 5, RoundingMode.HALF_UP)
					.divide(BigDecimal.valueOf(3600), 5, RoundingMode.HALF_UP);
		} else {
			materRate = BigDecimal.ZERO; // 无物料费用时返回0
		}
		deviceInfo.setMaterialRate(materRate);
        // 6 直接费率
		BigDecimal directRate = depreciationRate.add(powRate.add(materRate));
		// 保留四位小数，四舍五入
		directRate = directRate.setScale(4, BigDecimal.ROUND_HALF_UP);
		deviceInfo.setDirectRate(directRate);
		// 7 辅助费率
		BigDecimal indirectRate = deviceInfo.getDepreciationRate().multiply(deviceBaseInfo.getFzFl()).setScale(5,RoundingMode.HALF_UP);

		deviceInfo.setIndirectRate(indirectRate);



		//8 每小时设备成本
		BigDecimal hourly_equipment_cost = directRate
				.multiply(BigDecimal.valueOf(3600))  // 计算每小时成本
				.setScale(1, RoundingMode.HALF_UP);  // 保留1位小数（四舍五入）

		deviceInfo.setHourlyEquipmentCost(hourly_equipment_cost);

        //9 每小时辅助成本
		BigDecimal indirectRateHour = indirectRate.multiply(BigDecimal.valueOf(3600)).setScale(1,RoundingMode.HALF_UP);
		deviceInfo.setHourlyIndirectCost(indirectRateHour);

      //  10 人工费率
		UserRate userRate = userRateService.getOne(new QueryWrapper<UserRate>().eq("process_name",deviceInfo.getDeviceType()));
		if(userRate==null){

			throw new JeecgBootException("未找到人工费率，请先维护该类别的人工费率方可导入");

		}
        BigDecimal userR = userRate.getRate().setScale(6, RoundingMode.HALF_UP);
		deviceInfo.setUserRate(userR);
		deviceInfo.setHourlyLaborCost(new BigDecimal(0.0));
//		BigDecimal hourly_labor_cost = userR.subtract(deviceInfo.get)

		BigDecimal total_hourly_cost = hourly_equipment_cost.add(indirectRateHour);
		deviceInfo.setTotalHourlyCost(total_hourly_cost);
		deviceInfo.setIsNew(1);
		deviceInfo.setVersion(1);

		deviceInfoService.save(deviceInfo);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param deviceInfo
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-编辑")
	@ApiOperation(value="设备基础费率表-编辑", notes="设备基础费率表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody DeviceInfo deviceInfo) {
		DeviceBaseInfo deviceBaseInfo = deviceBaseInfoService.list().get(0);

		DeviceInfo deviceInfoOld= deviceInfoService.getById(deviceInfo.getId());
		deviceInfoOld.setIsNew(0);
		deviceInfoService.updateById(deviceInfoOld);




		// 1. 计算 oldValueW（除以10000，保留4位小数）
		BigDecimal tenThousand = BigDecimal.valueOf(10000);
		if(deviceInfo.getOldValue()!=null){
			BigDecimal oldValueW = deviceInfo.getOldValue()
					.divide(tenThousand, 4, RoundingMode.HALF_UP);
			deviceInfo.setOldValueW(oldValueW);
		}



		// 2. 计算 directRate（设备折旧费率）
		BigDecimal depreciationFactor = BigDecimal.ONE.subtract(deviceBaseInfo.getSbCz());
		BigDecimal usageInSeconds = BigDecimal.valueOf(3600);
		BigDecimal depreciationRate = BigDecimal.ZERO;
		if( deviceInfo.getOldValue()!=null){
			BigDecimal numerator = deviceInfo.getOldValue().multiply(depreciationFactor);
			BigDecimal denominator = new BigDecimal(deviceInfo.getUseMonth())
					.multiply(deviceBaseInfo.getSbZjDay())
					.multiply(deviceBaseInfo.getSbZjHour())
					.multiply(usageInSeconds);

			depreciationRate = numerator.divide(denominator, 5, RoundingMode.HALF_UP);
			deviceInfo.setDepreciationRate(depreciationRate);
		}else{
			deviceInfo.setDepreciationRate(BigDecimal.valueOf(0));
		}

		//3 电费率
		BigDecimal powRate = BigDecimal.valueOf(0);
		if(deviceInfo.getPower()==null || deviceInfo.getPowerConsumptionRatio()==null){
			deviceInfo.setPowRate(BigDecimal.valueOf(0));
		}else{
			powRate = deviceInfo.getPower().multiply(deviceInfo.getPowerConsumptionRatio()).multiply(deviceBaseInfo.getDf()).divide(BigDecimal.valueOf(3600),5,RoundingMode.HALF_UP);
			deviceInfo.setPowRate(powRate.setScale(5, BigDecimal.ROUND_HALF_UP));
			
		}

		//机物料费率
		// 4. 计算所有物料的月总费用（material1MonthUse * material1Price + ...）
		BigDecimal materRate = Stream.of(
				// 使用 Optional 包装，避免 NPE
				calculateMaterialCost(deviceInfo.getMaterial1MonthUse(), deviceInfo.getMaterial1Price()),
				calculateMaterialCost(deviceInfo.getMaterial2MonthUse(), deviceInfo.getMaterial2Price()),
				calculateMaterialCost(deviceInfo.getMaterial3MonthUse(), deviceInfo.getMaterial3Price()),
				calculateMaterialCost(deviceInfo.getMaterial4MonthUse(), deviceInfo.getMaterial4Price()),
				calculateMaterialCost(deviceInfo.getMaterial5MonthUse(), deviceInfo.getMaterial5Price()),
				calculateMaterialCost(deviceInfo.getMaterial6MonthUse(), deviceInfo.getMaterial6Price())
		)
				.filter(Objects::nonNull) // 过滤掉为null的物料费用
				.reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有非空物料费用

		// 5. 按基准值和时间单位折算费率
		if (materRate.compareTo(BigDecimal.ZERO) > 0) {
			materRate = materRate.divide(deviceBaseInfo.getJwlxhDay(), 5, RoundingMode.HALF_UP)
					.divide(deviceBaseInfo.getJwlxhHour(), 5, RoundingMode.HALF_UP)
					.divide(BigDecimal.valueOf(3600), 5, RoundingMode.HALF_UP);
		} else {
			materRate = BigDecimal.ZERO; // 无物料费用时返回0
		}
		deviceInfo.setMaterialRate(materRate);
		// 6 直接费率
		BigDecimal directRate = depreciationRate.add(powRate.add(materRate));
		// 保留四位小数，四舍五入
		directRate = directRate.setScale(4, BigDecimal.ROUND_HALF_UP);
		deviceInfo.setDirectRate(directRate);
		// 7 辅助费率
		BigDecimal indirectRate = deviceInfo.getDepreciationRate().multiply(deviceBaseInfo.getFzFl()).setScale(5,RoundingMode.HALF_UP);

		deviceInfo.setIndirectRate(indirectRate);



		//8 每小时设备成本
		BigDecimal hourly_equipment_cost = directRate
				.multiply(BigDecimal.valueOf(3600))  // 计算每小时成本
				.setScale(1, RoundingMode.HALF_UP);  // 保留1位小数（四舍五入）

		deviceInfo.setHourlyEquipmentCost(hourly_equipment_cost);

		//9 每小时辅助成本
		BigDecimal indirectRateHour = indirectRate.multiply(BigDecimal.valueOf(3600)).setScale(1,RoundingMode.HALF_UP);
		deviceInfo.setHourlyIndirectCost(indirectRateHour);

		//  10 人工费率
		UserRate userRate = userRateService.getOne(new QueryWrapper<UserRate>().eq("process_name",deviceInfo.getDeviceType()));
		if(userRate==null){

			throw new JeecgBootException("未找到人工费率，请先维护该类别的人工费率方可导入");

		}

		BigDecimal userR = userRate.getRate().setScale(3, RoundingMode.HALF_UP);
		deviceInfo.setUserRate(userR);
		deviceInfo.setHourlyLaborCost(new BigDecimal(0.0));
//		BigDecimal hourly_labor_cost = userR.subtract(deviceInfo.get)

		BigDecimal total_hourly_cost = hourly_equipment_cost.add(indirectRateHour);
		deviceInfo.setTotalHourlyCost(total_hourly_cost);
		deviceInfo.setIsNew(1);
		deviceInfo.setVersion(deviceInfoOld.getVersion()+1);
		deviceInfo.setId(null);
		deviceInfoService.save(deviceInfo);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-通过id删除")
	@ApiOperation(value="设备基础费率表-通过id删除", notes="设备基础费率表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		deviceInfoService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-批量删除")
	@ApiOperation(value="设备基础费率表-批量删除", notes="设备基础费率表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.deviceInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备基础费率表-通过id查询")
	@ApiOperation(value="设备基础费率表-通过id查询", notes="设备基础费率表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		DeviceInfo deviceInfo = deviceInfoService.getById(id);
		if(deviceInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(deviceInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param deviceInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DeviceInfo deviceInfo) {
        return super.exportXls(request, deviceInfo, DeviceInfo.class, "设备基础费率表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {





        return this.importExcelDevice(request, response, DeviceInfo.class);
    }
	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 protected Result<?> importExcelDevice(HttpServletRequest request, HttpServletResponse response, Class<DeviceInfo> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<DeviceInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();

				 for (int i = 0; i < list.size(); i++) {
					 DeviceBaseInfo deviceBaseInfo = deviceBaseInfoService.list().get(0);
                     DeviceInfo deviceInfo = list.get(i);

					 DeviceInfo deviceInfoS = deviceInfoService.getOne(new QueryWrapper<DeviceInfo>().eq("device_type",deviceInfo.getDeviceType()).eq("device_name_model",deviceInfo.getDeviceNameModel()));
                     if(deviceInfoS!=null){


						 throw new JeecgBootException("该信息已存在，请重新检查后导入！"+deviceInfoS.getDeviceType()+"/"+deviceInfoS.getDeviceNameModel());
					 }


					 // 1. 计算 oldValueW（除以10000，保留4位小数）
					 BigDecimal tenThousand = BigDecimal.valueOf(10000);

					 if(deviceInfo.getOldValue()!=null){
						 BigDecimal oldValueW = deviceInfo.getOldValue()
								 .divide(tenThousand, 4, RoundingMode.HALF_UP);
						 deviceInfo.setOldValueW(oldValueW);

					 }


					 // 2. 计算 directRate（设备折旧费率）
					 BigDecimal depreciationFactor = BigDecimal.ONE.subtract(deviceBaseInfo.getSbCz());
					 BigDecimal usageInSeconds = BigDecimal.valueOf(3600);
					 BigDecimal depreciationRate = BigDecimal.ZERO;
                    if( deviceInfo.getOldValue()!=null){
						BigDecimal numerator = deviceInfo.getOldValue().multiply(depreciationFactor);
						BigDecimal denominator = new BigDecimal(deviceInfo.getUseMonth())
								.multiply(deviceBaseInfo.getSbZjDay())
								.multiply(deviceBaseInfo.getSbZjHour())
								.multiply(usageInSeconds);

						 depreciationRate = numerator.divide(denominator, 6, RoundingMode.HALF_UP);
						deviceInfo.setDepreciationRate(depreciationRate);
					}else{
						deviceInfo.setDepreciationRate(BigDecimal.valueOf(0));
					}

					 //3 电费率
					 BigDecimal powRate = BigDecimal.valueOf(0);
					 if(deviceInfo.getPower()==null || deviceInfo.getPowerConsumptionRatio()==null){

						 deviceInfo.setPowRate(BigDecimal.valueOf(0));
					 }else{
						  powRate = deviceInfo.getPower().multiply(deviceInfo.getPowerConsumptionRatio()).multiply(deviceBaseInfo.getDf()).divide(BigDecimal.valueOf(3600),5,RoundingMode.HALF_UP);
						 deviceInfo.setPowRate(powRate.setScale(5, BigDecimal.ROUND_HALF_UP));
					 }


					 //机物料费率
					 // 4. 计算所有物料的月总费用（material1MonthUse * material1Price + ...）
					 BigDecimal materRate = Stream.of(
							 // 使用 Optional 包装，避免 NPE
							 calculateMaterialCost(deviceInfo.getMaterial1MonthUse(), deviceInfo.getMaterial1Price()),
							 calculateMaterialCost(deviceInfo.getMaterial2MonthUse(), deviceInfo.getMaterial2Price()),
							 calculateMaterialCost(deviceInfo.getMaterial3MonthUse(), deviceInfo.getMaterial3Price()),
							 calculateMaterialCost(deviceInfo.getMaterial4MonthUse(), deviceInfo.getMaterial4Price()),
							 calculateMaterialCost(deviceInfo.getMaterial5MonthUse(), deviceInfo.getMaterial5Price()),
							 calculateMaterialCost(deviceInfo.getMaterial6MonthUse(), deviceInfo.getMaterial6Price())
					 )
							 .filter(Objects::nonNull) // 过滤掉为null的物料费用
							 .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有非空物料费用

					 // 5. 按基准值和时间单位折算费率
					 if (materRate.compareTo(BigDecimal.ZERO) > 0) {
						 materRate = materRate.divide(deviceBaseInfo.getJwlxhDay(), 5, RoundingMode.HALF_UP)
								 .divide(deviceBaseInfo.getJwlxhHour(), 5, RoundingMode.HALF_UP)
								 .divide(BigDecimal.valueOf(3600), 5, RoundingMode.HALF_UP);
					 } else {
						 materRate = BigDecimal.ZERO; // 无物料费用时返回0
					 }
					 deviceInfo.setMaterialRate(materRate);
					 // 6 直接费率
					 BigDecimal directRate = depreciationRate.add(powRate.add(materRate));
					 // 保留四位小数，四舍五入
					 directRate = directRate.setScale(5, BigDecimal.ROUND_HALF_UP);
					 deviceInfo.setDirectRate(directRate);
					 // 7 辅助费率
					 BigDecimal indirectRate = deviceInfo.getDepreciationRate().multiply(deviceBaseInfo.getFzFl()).setScale(5,RoundingMode.HALF_UP);

					
					 deviceInfo.setIndirectRate(indirectRate);



					 //8 每小时设备成本
					 BigDecimal hourly_equipment_cost = directRate
							 .multiply(BigDecimal.valueOf(3600))  // 计算每小时成本
							 .setScale(1, RoundingMode.HALF_UP);  // 保留1位小数（四舍五入）

					 deviceInfo.setHourlyEquipmentCost(hourly_equipment_cost);

					 //9 每小时辅助成本
					 BigDecimal indirectRateHour = indirectRate.multiply(BigDecimal.valueOf(3600)).setScale(1,RoundingMode.HALF_UP);
					 deviceInfo.setHourlyIndirectCost(indirectRateHour);

					 //  10 人工费率
					 UserRate userRate = userRateService.getOne(new QueryWrapper<UserRate>().eq("process_name",deviceInfo.getDeviceType()));
					 if(userRate==null){

						 throw new JeecgBootException("未找到人工费率，请先维护该类别的人工费率方可导入");

					 }
					 BigDecimal userR = userRate.getRate().setScale(6, RoundingMode.HALF_UP);
					 deviceInfo.setUserRate(userR);
					 deviceInfo.setHourlyLaborCost(new BigDecimal(0.0));
//		BigDecimal hourly_labor_cost = userR.subtract(deviceInfo.get)
					 deviceInfo.setIsNew(1);
					 deviceInfo.setVersion(1);
					 BigDecimal total_hourly_cost = hourly_equipment_cost.add(indirectRateHour);
					 deviceInfo.setTotalHourlyCost(total_hourly_cost);
				 }



				 deviceInfoService.saveBatch(list);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }
}
